import { createForm, IVitalFormCtx, VitalForm } from 'vital';
import * as i18n from '@/locales';
import { MciRichEditor } from '@/components/complex';
import { MciButton, MciMessageBox, MciNotification } from '@/components/base';
import { TApprovalStatus } from '../../approval-helper';
import { useApprovalType } from '../Complete';
import { useDrawerStore } from '@/components/base/Drawer/store';
import { postInvestBatchAudit, postWorkflowApprovalBatchTaskComplete } from '@/api';
import { useMatterSelection } from '@/hooks/useMatterSelection';
import { ApprovalWidth } from '@/components/business/Approval/approval-helper';
import { px2RemValue } from '@/utils/rem';
import { batchProcessCallback } from '@/views/expand-process/process/io/brand/batch-mgu/utils';
import { useProcessBack } from '@/hooks/useProcessBack';
import { useAppStore } from '@/store/app';
const useHeight = () => {
  const height = ref('');
  const getHeight = () => {
    height.value = window.innerHeight - px2RemValue(400) + 'px';
  };
  onMounted(() => {
    document.addEventListener('resize', getHeight);
  });
  onUnmounted(() => {
    document.removeEventListener('resize', getHeight);
  });
  getHeight();
  return {
    height
  };
};

export const BatchApproval = defineComponent({
  props: {
    isNewAudit: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const formRef = ref(null as TNullable<IVitalFormCtx<{ comment: string }>>);
    const drawerStore = useDrawerStore();
    const appStore = useAppStore();
    const { backToProcess } = useProcessBack();
    const { text, updateApprovalType, approvalType } = useApprovalType();
    const { list, taskConfigId, matterType } = useMatterSelection();
    // console.log('matterType', matterType.value);
    const { height } = useHeight();
    const submitType = ref('success'); // reject
    const config = createForm({
      attrs: {
        hideRequiredAsterisk: false,
        labelPosition: 'top'
      },
      initModel: {
        comment: ''
      },
      layout: {
        cols: 1
      },
      formItems: [
        {
          attrs: {
            label: i18n.t('审批意见'),
            rules: [
              {
                validator: (rule: any, value: string, cb: TAnyFunction) => {
                  if (!!value || submitType.value === 'success') {
                    cb();
                    return;
                  }
                  // 驳回 必填审批意见
                  cb(new Error('请输入审批意见'));
                }
              }
            ]
          },
          // rulePresets: ['required'],
          fields: [
            {
              prop: 'comment', //
              comp: (prop, model) => {
                return (
                  <MciRichEditor
                    height={height.value}
                    v-model={model.comment}
                    onChange={() => drawerStore.changeModify(true)}
                    placeholder={i18n.t('请输入审批意见')}
                  />
                );
              }
            }
          ]
        }
      ]
    });

    /**
     * 后续新的批量审批都使用该接口
     */
    const handleApproval = async (comment: string) => {
      const taskIds = list.value.map((item) => item.taskId) as string[];
      await postWorkflowApprovalBatchTaskComplete({
        approvalStatus: approvalType.value,
        taskIds,
        comment,
        userId: appStore.mcisaas?.userId
      });
      MciNotification.success('提交成功');
      drawerStore.changeModify(false);
      setTimeout(() => {
        backToProcess('refresh');
      }, 100);
    };
    // 处理审批意见
    const confirmHandle = async () => {
      const { comment = '' } = formRef.value?.getModel() || {};
      if (props.isNewAudit) {
        return await handleApproval(comment);
      }
      const investmentIds = list.value.map((item) => item.investmentId!);
      const res = await postInvestBatchAudit({
        investmentIds,
        comment,
        taskConfigId: taskConfigId.value!,
        approvalStatus: approvalType.value
      });
      MciNotification.success('提交成功');
      await batchProcessCallback(res);
      drawerStore.changeModify(false);
      setTimeout(() => {
        backToProcess('refresh');
      }, 100);
    };
    const showDialog = async (status: TApprovalStatus) => {
      updateApprovalType(status);
      submitType.value = status === 'AGREE' ? 'success' : 'reject';
      await formRef.value?.validate();
      MciMessageBox.confirm(text.value, i18n.t('提示'), {
        requestLoading() {
          return confirmHandle();
        }
      });
    };
    return {
      config,
      matterType,
      formRef,
      showDialog
    };
  },
  render() {
    if (this.matterType !== 'approval') {
      return null;
    }
    return (
      <div style={{ width: ApprovalWidth }} class="h-full">
        <VitalForm ref="formRef" config={this.config} />
        <div class="flex mt-12px">
          <MciButton type="primary" class="flex-1 " onClick={() => this.showDialog('AGREE')}>
            {i18n.t('同意')}
          </MciButton>
          <MciButton class="flex-1 " onClick={() => this.showDialog('REJECT')}>
            {i18n.t('驳回')}
          </MciButton>
        </div>
      </div>
    );
  }
});
